#include <iostream>
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
// 创建5个线程
static int const gnum = 5;
int tickets = 1000;
struct fun
{
    std::string name;
    pthread_mutex_t *mutex;
};
void *routine(void *arg)
{
    fun *f = (fun *)arg;
    std::string name = f->name;
    // 加锁

    while (1)
    {
        pthread_mutex_lock((f->mutex));
        if (tickets > 0)
        {
           // sleep(1);
            std::cout << "我是" << f->name << "我抢到了一张票" <<tickets<< std::endl;
            tickets--;
            // 解锁
            pthread_mutex_unlock(f->mutex);
        }
        else
        {
            pthread_mutex_unlock(f->mutex);
            break;
        }
    }
return nullptr;
    // 加锁
}


void BulidThread(int sum,pthread_mutex_t *mutex)
{


    pthread_t tid = 0;
    for (int i = 0; i < sum; i++)
    {
        fun*f=new fun();
        char *name = new char[64];
         snprintf(name, 64, "thread-%d", i);
        f->name = name;
        f->mutex=mutex;

       
        pthread_create(&tid, nullptr, routine, (void *)f);
    }
}

int main()
{
    //先初始化锁
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);
  
BulidThread(gnum,&mutex);
sleep(1000);
return 0;
}